package com.zyd.module.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zyd.common.util.*;
import com.zyd.enums.GlobalConstant;
import com.zyd.module.admin.model.*;
import com.zyd.module.admin.service.*;
import com.zyd.module.admin.vo.ProductInfoVo;
import com.zyd.module.admin.vo.UploadResponse;
import com.zyd.module.admin.vo.base.PageResultVo;
import com.zyd.module.admin.vo.base.ResponseVo;
import io.swagger.annotations.Api;
import lombok.SneakyThrows;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import java.lang.reflect.Array;
import java.util.*;


import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;


/**
 * 
 *
 * @author hui
 * @email *****@mail.com
 * @date 2022-04-04 00:17:38
 */
@Controller
@RequestMapping("/product")
public class ProductInfosController {
    @Autowired
    private ProductInfosService productInfosService;

    @Autowired
    private ProductTypeService typeService;

    @Autowired
    private OssService ossService;
    @Autowired
    private RedisService redisService;

    @Autowired
    private ProductImageService productImageService;
    /**
     * 跳转到页面
     */
    @ApiOperation(value = "产品列表")
    @GetMapping("/list")
    public String productList(Model model) {
        List<ProductType> typeEntities = typeService.selectList();
        model.addAttribute("typeList",typeEntities);
        return CoreConst.ADMIN_PREFIX + "product/list";
    }

    @ApiOperation(value = "获取产品列表")
    @PostMapping("/table")
    @ResponseBody
    public PageResultVo productTable(ProductInfoVo infoVo, Integer pageNumber, Integer pageSize) {
        IPage<ProductInfos> page = new Pagination<>(pageNumber, pageSize);
        List<ProductInfos> productInfosList = productInfosService.findProductPages(page, infoVo);
        return ResultUtil.table(productInfosList, page.getTotal());
    }

    @ApiOperation("跳转到添加页面")
    @GetMapping("/add")
    public String productAdd(Model model){
        ProductInfos productInfos=new ProductInfos();
        List<ProductType> typeList=typeService.selectTypeNodes();
        model.addAttribute("product",productInfos);
        model.addAttribute("typeList",typeList);
        return CoreConst.ADMIN_PREFIX + "product/publish";
    }

    @ApiOperation("跳转到编辑页面")
    @GetMapping("/edit")
    public String productEdit(HttpServletRequest request,Model model,String id){
        ProductInfos productInfos=productInfosService.getAndThumbnailById(id);
        String addr = IpUtil.getIpAddr(request);
        redisService.set("id:"+addr,id);
        redisService.set("name:"+addr,productInfos.getProName());
        List<ProductType> typeList=typeService.selectTypeNodes();
        List<ProductImage> showList=productImageService.selectByImgTypeList(id,GlobalConstant.PRODUCT_SHOW);
        List<ProductImage> detailList=productImageService.selectByImgTypeList(id,GlobalConstant.PRODUCT_DETAIL);
        model.addAttribute("showList",showList);
        model.addAttribute("detailList",detailList);
        model.addAttribute("product",productInfos);
        model.addAttribute("typeList",typeList);
        return CoreConst.ADMIN_PREFIX + "product/publish";
    }

    @ResponseBody
    @PostMapping("/del_img")
    public ResponseVo del_img(String imgid){
        boolean remove = productImageService.removeFileById(imgid);
        if (remove){
            return ResultUtil.success("删除图片成功！");
        }else {
            return ResultUtil.success("删除图片失败！");
        }
    }
    @ResponseBody
    @PostMapping("/upload")
    public ResponseVo upload(HttpServletRequest request) {
        // SpringMVC 文件上传
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> files = multipartRequest.getFileMap();
        String addr = IpUtil.getIpAddr(request);
        String proid = (String)redisService.get("id:" + addr);
        String proname = (String)redisService.get("name:" + addr);
        if (files.get("ssi-upshow")!=null){
            MultipartFile image = files.get("ssi-upshow");
            UploadResponse response = ossService.upload(image);
            if (response.getStatus()== CoreConst.SUCCESS_CODE){
                ProductImage showImg=new ProductImage();
                showImg.setProId(proid);
                showImg.setProImg(response.getUrl());
                showImg.setImgDesc(proname+"展示图");
                showImg.setImgType(GlobalConstant.PRODUCT_SHOW);
                productImageService.save(showImg);
                return ResultUtil.success("上传图片成功！",response.getUrl());
            }else {
                return ResultUtil.error("上传图片失败！",response.getMsg());
            }
        }

        if (files.get("ssi-updetail")!=null){
            MultipartFile image = files.get("ssi-updetail");
            UploadResponse response = ossService.upload(image);
            if (response.getStatus()== CoreConst.SUCCESS_CODE){
                ProductImage detailImg=new ProductImage();
                detailImg.setProId(proid);
                detailImg.setProImg(response.getUrl());
                detailImg.setImgDesc(proname+"详情图");
                detailImg.setImgType(GlobalConstant.PRODUCT_DETAIL);
                productImageService.save(detailImg);
                return ResultUtil.success("上传图片成功！",response.getUrl());
            }else {
                return ResultUtil.error("上传图片失败！",response.getMsg());
            }
        }
        return ResultUtil.error("上传图片失败！");
    }

    @PostMapping("/save")
    @ResponseBody
    @Transactional
    @CacheEvict(value = "product", allEntries = true)
    public ResponseVo save(ProductInfos productInfos) {
        try {
            String id= UUIDUtil.getUniqueIdByUUId();
            productInfos.setId(id);
            productInfos.setLookCount(0);
            boolean save = productInfosService.save(productInfos);
            if (save){
                if (productInfos.getImgUrl()!=null&&!"".equals(productInfos.getImgUrl())){
                    ProductImage image=new ProductImage();
                    image.setProId(id);
                    image.setImgDesc(productInfos.getProName()+"的缩略图");
                    image.setProImg(productInfos.getImgUrl());
                    image.setImgType(GlobalConstant.PRODUCT_THUMBNAIL);
                    productImageService.save(image);
                }
                return ResultUtil.success("保存产品信息成功",id);
            }
            return ResultUtil.error("保存产品信息失败");
        } catch (Exception e) {
            return ResultUtil.error("保存产品信息失败");
        }
    }

    @PostMapping("/update")
    @ResponseBody
    @Transactional
    @CacheEvict(value = "product", allEntries = true)
    public ResponseVo update(ProductInfos productInfos) {
        try {
            boolean save = productInfosService.updateById(productInfos);
            if (save){
                if (productInfos.getImgUrl()!=null&&!"".equals(productInfos.getImgUrl())){
                    QueryWrapper<ProductImage> queryWrapper=new QueryWrapper<>();
                    queryWrapper.eq("pro_id",productInfos.getId());
                    queryWrapper.eq("img_type",GlobalConstant.PRODUCT_THUMBNAIL);
                    ProductImage image=productImageService.getOne(queryWrapper);
                    productImageService.removeById(image.getId());
                    if (image!=null){
                        image.setProId(productInfos.getId());
                        image.setImgDesc(productInfos.getProName()+"的缩略图");
                        image.setProImg(productInfos.getImgUrl());
                        image.setImgType(GlobalConstant.PRODUCT_THUMBNAIL);
                        productImageService.save(image);
                    }
                }
                return ResultUtil.success("更新产品信息成功");
            }
            return ResultUtil.error("更新产品信息失败");
        } catch (Exception e) {
            return ResultUtil.error("更新产品信息失败");
        }
    }


    @ApiOperation(value = "删除")
    @PostMapping("/delete")
    @ResponseBody
    public ResponseVo deleteCustomer(String id) throws InterruptedException {
        ProductInfos entity =productInfosService.getById(id);
        if (entity==null) {
            return ResultUtil.error("产品信息不存在！");
        }
        QueryWrapper<ProductImage> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("pro_id",id);
        List<ProductImage> imgList=productImageService.selectByProIdList(id);
        if (imgList!=null&&imgList.size()>0){
            for (int i = 0; i < imgList.size(); i++) {
                productImageService.removeFileById(imgList.get(i).getId());
            }

            boolean delPro = productInfosService.removeById(id);
                if (delPro) {
                    return ResultUtil.success("删除该产品及关联数据成功!");
                } else {
                    return ResultUtil.error("删除产品图片成功，删除产品信息失败！");
                }

        }else {
            boolean delPro = productInfosService.removeById(id);
            if (delPro) {
                return ResultUtil.success("删除该产品及关联数据成功");
            } else {
                return ResultUtil.error("删除产品信息失败！");
            }
        }
    }

    @SneakyThrows
    @ApiOperation(value = "批量删除")
    @PostMapping("/batch/delete")
    @ResponseBody
    public ResponseVo deleteBatch(@RequestParam("ids[]") String[] ids) {
        Integer countImg= null;
        countImg = productImageService.removeByProIds(Arrays.asList(ids));
        Integer countPro = productInfosService.removeProductrByIds(Arrays.asList(ids));
        if (countImg>0){
            if (countPro==ids.length) {
                return ResultUtil.success("批量删除产品信息成功！");
            } else if (countPro>0&&countPro<ids.length){
                return ResultUtil.success("共删除了"+countPro+"条数据，未删除产品信息可能存在问题！");
            } else{
                return ResultUtil.error("批量删除产品信息失败");
            }
        }else {
            return ResultUtil.error("批量删除产品信息失败");
        }

    }



}
